import { request } from '@/utils/request';
import { Storage } from '@/utils/Storage';
import { AUTH_TOKEN_KEY } from '@/enums/cacheEnum';
import { RequestEnum } from '@/enums/httpEnum';

interface IProps {
  initParams?: any;
  apiKey: string;
  type?: 'POST' | 'GET';
  isLoginRequired?: boolean;
  isMount?: boolean;
  showLoading?: boolean;
}

const useRequestDetail = ({
  initParams,
  apiKey,
  type = RequestEnum.GET,
  isLoginRequired = false,
  isMount = true,
  showLoading = true,
}: IProps) => {
  const params = ref({ ...initParams });
  const loading = ref(false);
  const detailData: any = ref({});

  const getDetail = async () => {
    loading.value = true;
    const sendParams = {
      ...params.value,
    };
    const paramsData = type === RequestEnum.GET ? { params: sendParams } : { data: sendParams };
    const res = await request({ url: apiKey, method: type, ...paramsData });

    loading.value = false;

    if (!res.data) return;
    detailData.value = res.data;
  };

  onMounted(async () => {
    const token = Storage.get(AUTH_TOKEN_KEY);
    if (isLoginRequired && !token) {
      return;
    }
    if (!isMount) return;
    await getDetail();
  });

  const setParams = (value) => {
    params.value = value;
  };

  watch(params, () => {
    detailData.value = {};
    getDetail().then();
  });

  return { detailData, params, setParams, loading, getDetail };
};

export default useRequestDetail;
